#include "structs.hh"

#include <iostream>
#include <fstream>
#include <cstdlib>

#include <boost/foreach.hpp>
#define feach BOOST_FOREACH


using namespace std;

#ifdef BENCHMARK
#include <boost/chrono.hpp>
using namespace boost::chrono;
static system_clock::time_point start;
#endif

const unsigned int TIME_LIMIT = 60;


Dataset readDataSet ( const string& filename ) {
  ifstream ifs ( filename.c_str() );

  if ( !ifs ) {
    cerr << "File not found..." << endl;
    exit(0);
  }

  Dataset result;
  ifs >> result.numberOfBTS;
  ifs >> result.capacity;
  result.stations = new BTS[result.numberOfBTS];

  for( uint i = 0; i < result.numberOfBTS; ++i ) {
    ifs >> result.stations[i].id;
    ifs >> result.stations[i].incomes;
    ifs >> result.stations[i].subscribers;
    result.stations[i].known = false;
  }

  ifs.close();

  return result;
}

void displaySolution ( Dataset d, vector < BTS* > solution ) {
  uint totalIncome = 0;
  uint totalSubscribers = 0;

  cout << "Number of stations : " << solution.size() << endl;
  cout << "Stations : ";
  feach ( BTS* b, solution ) {
    totalIncome += b->incomes;
    totalSubscribers += b->subscribers;
    cout << b->id << ", ";
  }
  cout << endl;
  
  cout << "Incomes : " << totalIncome << endl;
  cout << "Subscribers : " << totalSubscribers << endl;
  cout << "Capacity : " << d.capacity << endl;
}

void displaySolution ( Dataset d, BTS** solutions ) {
  vector < BTS* > finalSolution;
  uint i = 0; 
  while ( solutions[i] != NULL ) finalSolution.push_back ( solutions[i++] );

  displaySolution ( d, finalSolution );
}


int BTS_Cmp ( const void* a, const void* b ) {
  BTS* btsA = (BTS*)a; BTS* btsB = (BTS*)b;

  double perCapitaA = (double)btsA->incomes / (double)btsA->subscribers;
  double perCapitaB = (double)btsB->incomes / (double)btsB->subscribers;

  return (perCapitaA > perCapitaB) ? (-1)
    : ((perCapitaA < perCapitaB) ? 1 : 0); 
}

void startTimer () {
#ifdef BENCHMARK
  start = system_clock::now();
#endif
}

void stopTimer () {
#ifdef BENCHMARK
  cout <<
    duration_cast<microseconds>( system_clock::now() - start ).count() << endl;
#endif
}

void checkTime () {
#ifdef BENCHMARK
   if ( duration_cast<microseconds>( system_clock::now() - start ).count() >= TIME_LIMIT * 1000000 ) {
    cout << -1 << endl;
     exit(1);
   }
#endif
}
